<template>
  <div>
    <Row :gutter="10">
      <Col>
      <Card>
        <Row class="live_wrapper clearfix">
          <Button type="primary"
                  style="float:right;width:90px;height: 34px;font-size: 14px;"
                  @click="addGood">添加</Button>
          <Input v-model="filter.name"
                 @on-search="search"
                 search
                 enter-button="查询"
                 placeholder="请输入商品名称"
                 style="width:290px; margin-right: 10px;float: right;top:0;font-size: 14px;" />
          <Select v-model="filter.cate_id"
                  style="float:right; width: 200px;margin-right: 35px;"
                  @on-change="search"
                  placeholder="选择商品品类">
            <Option value="0">全部</Option>
            <Option :value="item.id"
                    v-for="(item, index) in cate_list">{{item.name}}</Option>
          </Select>
        </Row>
        <Row class="margin-top-10 table_pattern table_pattern2">
          <Table :loading="loading"
                 :columns="columns"
                 :data="list"></Table>
        </Row>
        <Row class="margin-top-10">
          <Page :total="pagenation.totalPage"
                :page-size="pagenation.perPage"
                :current="pagenation.currentPage"
                show-elevator
                show-total
                @on-change="change"></Page>
        </Row>
      </Card>
      </Col>
    </Row>
    <Modal v-model="edit"
           :title="title"
           width="800px"
           :mask-closable="false"
           class="goods_modal"
           :z-index='100'>
      <Form :model="formValidate"
            ref="formValidate"
            :label-width="120">
        <FormItem label="商品名称"
                  prop="name"
                  class="label_required">
          <Input v-model="formValidate.name"
                 placeholder="请输入商品名称"
                 style='width:60%' />
        </FormItem>
        <FormItem label="商品封面图"
                  prop="cover">
          <div>
            <Row type="flex"
                 justify="start"
                 align="middle"
                 class="height-100">
              <div style="display: block;text-align: center;">
                <Upload ref="upload"
                        :max-size="500"
                        :show-upload-list="false"
                        action="https://up.qiniup.com"
                        :on-format-error="handleFormatError"
                        :before-upload="handleBeforeUpload"
                        :on-progress="handleProgress"
                        :on-success="handleSuccess"
                        :on-error="handleError"
                        :data="{token:upload_token}">
                  <Button cover="ios-cloud-upload-outline">上传文件</Button>
                  <span style="padding-left:20px; color:#999">建议尺寸: 150*120px，JPG、PNG、JPEG格式，图片小于500KB</span>
                </Upload>
              </div>
            </Row>
            <Row class="margin-top-20">
              <div class=""
                   v-if="this.formValidate.cover">
                <template>
                  <div class="demo-upload-list">
                    <img :src="this.formValidate.cover"
                         style='width:150px; height:100px'>
                    <div class="demo-upload-list-cover">
                      <Icon type="ios-eye-outline"
                            @click.native="handleView(this.formValidate.cover)"></Icon>
                      <Icon type="ios-trash-outline"
                            @click.native="handleRemove()"></Icon>
                    </div>
                  </div>
                </template>
              </div>
            </Row>
          </div>
        </FormItem>
        <FormItem label="商品分类"
                  prop="cate_id">
          <Select v-model="formValidate.cate_id"
                  style="width:200px">
            <Option v-for="(item, key) in cate_list"
                    :value="item.id"
                    :key="key">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="商品内容"
                  prop="content"
                  class="label_required">
          <NEditor v-if="!spinShow"
                   :msg="formValidate.content"
                   @changeMsg="changeMsg"></NEditor>
        </FormItem>
        <FormItem label="销售类型"
                  prop="type">
          <RadioGroup v-model="formValidate.type">
            <Radio label="1">自营设备</Radio>
            <Radio label="2">三方设备</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="是否需要支付"
                  prop="is_pay"
                  v-if='0'>
          <RadioGroup v-model="formValidate.is_pay">
            <Radio label="1">是</Radio>
            <Radio label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="发货方式"
                  prop="is_zl">
          <RadioGroup v-model="formValidate.is_zl">
            <Radio label="1">自提</Radio>
            <Radio label="0">运输</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="商品单位"
                  prop="unit">
          <Input v-model="formValidate.unit"
                 placeholder="商品单位"
                 style="width: 370px;" />
        </FormItem>
        <FormItem label="租赁单位"
                  prop="unit_type">
          <RadioGroup v-model="formValidate.unit_type">
            <Radio label="2">天</Radio>
            <Radio label="3">月</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="优先级"
                  prop="sort">
          <Input v-model="formValidate.sort"
                 placeholder="商品优先级"
                 style="width: 370px;" />
          <span style='margin-left:10px; color:#f00'>数值越大优先显示</span>
        </FormItem>
        <FormItem label="商品销量"
                  prop="sale_count">
          <Input v-model="formValidate.sale_count"
                 placeholder="商品销量"
                 style="width: 370px;" />
        </FormItem>
        <FormItem label="是否有规格"
                  prop="is_have_specs">
          <RadioGroup v-model="formValidate.is_have_specs">
            <Radio label="1">是</Radio>
            <Radio label="0">否</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="规格品类"
                  v-if="formValidate.is_have_specs==1">
          <div style="width:700px;">
            <div style="width:160px; float:left">
              <Tree :data="specs_list"
                    show-checkbox
                    multiple
                    @on-check-change='getCheckedNodes'></Tree>
            </div>
          </div>
        </FormItem>
        <FormItem label="商品价格"
                  v-if="formValidate.is_have_specs==1">
          <Button type="primary"
                  @click="setPrice()"
                  style="width: 90px;height: 35px;border-radius: 0;font-size: 14px;">设置价格</Button>
        </FormItem>
        <FormItem label="商品价格"
                  prop="price"
                  v-if="formValidate.is_have_specs==0">
          <Input v-model="formValidate.price"
                 placeholder="商品价格"
                 style="width: 370px;" />
        </FormItem>
        <FormItem>
          <Button :loading="saving"
                  type="primary"
                  @click="handleSubmit"
                  style="width: 90px;height: 35px;border-radius: 0;font-size: 14px;">提交</Button>
        </FormItem>
      </Form>
    </Modal>
    <Modal v-model="set_good_price"
           title="设置商品价格"
           width="600px"
           :mask-closable="false"
           class="goods_modal"
           :z-index='100'>
      <table>
        <tr>
          <td style='width:200px'
              v-if='0'>商品规格组合编码</td>
          <td style='width:300px'>商品规格组合名称</td>
          <td style='width:300px'>商品规格组合价格</td>
        </tr>
        <tr v-for="(item, index) in price_list">
          <td v-if='0'>{{item.specs_code}}</td>
          <td>{{item.specs_name}}</td>
          <td><Input v-model="item.specs_price"
                   placeholder="请输入商品规格组合价格"
                   style="width: 200px" /></td>
        </tr>
      </table>
      <Button type="primary"
              @click="handleSubmitPrice"
              style="width: 90px;height: 35px;border-radius: 0;font-size: 14px; margin-left:200px;  margin-top:20px">确定</Button>
    </Modal>
    <Modal v-model="show_audit_good"
           title="审核"
           width="600px"
           :mask-closable="false"
           class="public_modal_header edit_modal">
      <div style="width: 80%;margin: 0 auto;padding: 50px;">
        <RadioGroup v-model="audit_status"
                    style="display: flex;justify-content: center;align-items: center;">
          <Radio label="1"
                 style="font-size: 15px;margin-right:50px;">审核通过</Radio>
          <Radio label="2"
                 style="font-size: 15px;">审核失败</Radio>
        </RadioGroup>
        <Input v-model="audit_content"
               type="textarea"
               :rows="5"
               v-if='audit_status==2'
               style="margin-top:20px"
               placeholder='请输入审核拒绝原因' />
      </div>
      <div class="btns">
        <Button @click.stop="show_audit_good = false">取消</Button>
        <Button @click.stop="auditGoodOk"
                type="primary"
                style="margin-left:15px;">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import config from '@/config'
import { getQiniu, goodList, editGood, changeGoodStatus, cateListForSelect, specsListForSelect, getGoodPriceList, goodDetail, auditGood } from '@/api/main'
export default {
  data () {
    return {
      upload_token: '',
      qiniu_url: '',
      visible: false,
      imgName: '',
      spinShow: false,
      pagenation: {},
      columns: [
        {
          key: 'name',
          title: '商品名称',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.name)
          },
        },
        {
          key: 'cover',
          title: '商品封面图',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              {
                style: {
                  backgroundImage: 'url(' + params.row.cover + ')',
                  width: '150px',
                  height: '120px',
                  objectFit: 'cover',
                  margin: '10px auto',
                  position: 'relative',
                  cursor: 'pointer',
                  backgroundSize: 'cover',
                },
                on: {
                  click: e => {
                  },
                },
              }
            )
          },
        },
        {
          key: 'cate_name',
          title: '所属品类',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.cate_name)
          },
        },
        {
          key: 'is_zl',
          title: '运输方式',
          align: 'center',
          render: (h, params) => {
            return h('strong', parseInt(params.row.is_zl) ? '自提' : '运输')
          },
        },
        {
          key: 'type',
          title: '销售类型',
          align: 'center',
          render: (h, params) => {
            return h('strong', parseInt(params.row.type) == 1 ? '自营设备' : '三方设备')
          },
        },
        {
          key: 'unit',
          title: '商品单位',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.unit)
          },
        },
        {
          key: 'unit_type',
          title: '租赁单位',
          align: 'center',
          render: (h, params) => {
            return h('strong', parseInt(params.row.unit_type) == 2 ? '按天' : '按月')
          },
        },
        /*{
            key: 'sort',
            title: '优先级',
            align: 'center',
            render: (h, params) => {
                return h('strong', params.row.sort)
            },
        },
        {
            key: 'audit_status_name',
            title: '审核状态',
            align: 'center',
            render: (h, params) => {
                return h('strong', parseInt(params.row.good_type) == 1 ? '' : params.row.audit_status_name)
            },
        },*/
        {
          key: 'status',
          title: '状态',
          width: 150,
          align: 'center',
          render: (h, params) => h('i-switch', {
            props: {
              value: params.row.status,
              size: 'large',
              'true-value': 1,
              'false-value': 0
            },
            on: {
              'on-change': () => {
                this.changeGoodStatus(params.row)
              }
            }
          }, [
            h('span', {
              slot: 'open',
              domProps: {
                innerHTML: '开启'
              }
            }),
            h('span', {
              slot: 'close',
              domProps: {
                innerHTML: '关闭'
              }
            })
          ]
          )
        },
        {
          key: 'created_time',
          title: '创建时间',
          align: 'center',
          render: (h, params) => {
            return h('strong', params.row.created_time)
          },
        },
        {
          title: '操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  style: {
                    marginBottom: '5px',
                    marginRight: '5px',
                    border: 0,
                    background: 'transparent',
                    fontSize: '14px',
                    color: '#377EEF'
                  },
                  on: {
                    click: () => {
                      this.editGood(params.row)
                    },
                  },
                },
                '编辑',
              ),
              h(
                'Poptip',
                {
                  props: {
                    confirm: true,
                    title: '您确定要删除该商品吗?',
                    transfer: true,
                  },
                  on: {
                    'on-ok': () => {
                      let obj = {}
                      obj.id = params.row.id
                      obj.status = -1
                      changeGoodStatus(obj).then(res => {
                        if (res.code === 0) {
                          this.$Message.success('操作成功')
                          this.getGoodList()
                        } else {
                          this.$Message.error(res.text)
                        }
                      })
                    },
                  },
                },
                [
                  h(
                    'Button',
                    {
                      style: {
                        marginBottom: '5px',
                        marginRight: '5px',
                        border: 0,
                        background: 'transparent',
                        fontSize: '14px',
                        color: '#377EEF'
                      },
                      props: {
                        placement: 'top',
                        size: 'small',
                      },
                    },
                    '删除',
                  ),
                ],
              ),
              h(
                'Button',
                {
                  style: {
                    marginBottom: '5px',
                    marginRight: '5px',
                    border: 0,
                    background: 'transparent',
                    fontSize: '14px',
                    color: '#377EEF',
                    display: (params.row.good_type == 2 && params.row.audit_status == 0) ? 'inline-block' : 'none'
                  },
                  on: {
                    click: () => {
                      this.auditGood(params.row)
                    },
                  },
                },
                '审核',
              ),
            ])
          },
        },
      ],
      edit: false,
      title: '添加商品',
      list: [],
      cate_list: [],
      specs_list: [],
      loading: true,
      saving: false,
      formValidate: {
        id: 0,
        name: '',
        cover: '',
        content: '',
        cate_id: 0,
        type: '1',
        is_zl: '1',
        unit: '台',
        unit_type: '2',
        is_pay: '1',
        sort: 0,
        is_have_specs: '1',
        specs_ids: '',
        specs_obj_str: '',
        specs_price_str: '',
        price: '',
      },
      filter: {
        page: 0,
        name: '',
        cate_id: 0
      },
      specs_arr: [],
      price_list: [],
      set_good_price: false,
      is_get_price_list: false,
      show_audit_good: false,
      audit_status: '1',
      audit_content: '',
      item_id: 0,
    }
  },
  methods: {
    change: function (page) {
      this.loading = true
      this.filter.page = page - 1
      this.getGoodList()
    },
    search: function () {
      this.filter.page = 0
      this.getGoodList()
    },
    changeMsg (msg) {
      this.formValidate.content = msg
    },
    addGood: function () {
      this.spinShow = true
      this.formValidate.id = 0
      this.formValidate.content = ''
      this.title = '添加商品'
      this.handleReset('formValidate')
      let obj_specs = {}
      obj_specs.type = 2
      obj_specs.specs_id = ''
      specsListForSelect(obj_specs).then(res => {
        this.specs_list = res.data
        this.edit = true
        setTimeout(() => {
          this.spinShow = false
        }, 1)
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
    },
    editGood: function (obj) {
      this.spinShow = true
      let good_obj = {}
      good_obj.id = obj.id
      goodDetail(good_obj).then(res => {
        this.formValidate = Object.assign({}, res.data)
        this.formValidate.type = this.formValidate.type.toString()
        this.formValidate.unit_type = this.formValidate.unit_type.toString()
        this.formValidate.is_have_specs = this.formValidate.is_have_specs.toString()
        this.formValidate.is_zl = this.formValidate.is_zl.toString()
        this.formValidate.is_pay = this.formValidate.is_pay.toString()
        this.price_list = JSON.parse(res.data.specs_price_str)
        this.is_get_price_list = true
        this.title = '编辑商品'
        let obj_specs = {}
        obj_specs.type = 2
        obj_specs.specs_ids = obj.specs_ids
        specsListForSelect(obj_specs).then(res1 => {
          this.specs_list = res1.data
          this.edit = true
          setTimeout(() => {
            this.spinShow = false
          }, 1)
        })
      })
    },
    changeGoodStatus (item) {
      let obj = {}
      obj.id = item.id
      obj.status = parseInt(item.status) ? 0 : 1
      changeGoodStatus(obj).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.getGoodList()
        } else {
          this.$Message.error(res.text)
        }
      })
    },
    auditGood (item) {
      this.item_id = item.id
      this.show_audit_good = true
    },
    auditGoodOk () {
      if (this.audit_status == 2 && this.audit_content == '') {
        this.$Message.error('请输入拒绝理由'); return;
      }
      let obj = {}
      obj.id = this.item_id
      obj.audit_status = this.audit_status
      obj.audit_content = this.audit_content
      auditGood(obj).then(res => {
        if (res.code == 0) {
          this.$Message.success('操作成功');
          this.getGoodList()
          this.show_audit_good = false
        } else {
          this.$Message.error(res.text);
        }
      })
    },
    getCheckedNodes (arr) {
      //console.log(arr);return;
      let _this = this
      this.is_get_price_list = false
      let specs_ids = ""
      let id_arr_all = []
      if (arr.length) {
        var res_sort = this.sort_pro(arr, ['parent_id']);
        for (let i = 0; i < res_sort.length; i++) {
          if (res_sort[i].parent_id > 0) {
            let id_arr = []
            for (let j = 0; j < res_sort[i].children.length; j++) {
              id_arr.push(res_sort[i].children[j].id)
            }
            id_arr_all.push(id_arr)
          }
        }
        for (let i = 0; i < arr.length; i++) {
          let obj = {}
          if (arr[i].parent_id > 0) {
            specs_ids += arr[i].id + ','
          }
        }
        specs_ids = specs_ids.substr(0, specs_ids.length - 1)
      }
      //console.log(id_arr_all);
      //console.log(JSON.stringify(id_arr_all));return;
      _this.formValidate.specs_ids = specs_ids
      _this.specs_arr = id_arr_all
      _this.formValidate.specs_obj_str = id_arr_all.length ? JSON.stringify(id_arr_all) : ''
    },
    sort_pro (data, keys = []) {     //keys可以传一个数组
      var c = [];
      var d = {};
      for (var element of data) {
        let element_keyStr = "";
        let element_key = [];
        let element_keyObj = {};
        for (var key of keys) {
          element_key.push(element[key]);
          element_keyObj[key] = element[key];
        }
        element_keyStr = element_key.join("_");
        if (!d[element_keyStr]) {
          c.push({
            ...element_keyObj,
            children: [element]
          });
          d[element_keyStr] = element;
        } else {
          for (var ele of c) {
            let isTrue = keys.some(key => {
              return ele[key] != element[key];
            });
            if (!isTrue) {
              ele.children.push(element);
            }
          }
        }
      }
      return c;
    },
    setPrice () {
      if (this.formValidate.specs_ids == '') {
        this.$Message.error("请先选择商品规格"); return;
      }
      if (this.is_get_price_list) {
        this.set_good_price = true
      } else {
        let obj = {}
        obj.specs_obj_str = this.formValidate.specs_obj_str
        getGoodPriceList(obj).then(res => {
          if (res.code == 0) {
            this.price_list = res.data
            this.set_good_price = true
            this.is_get_price_list = true
          }
        })
      }
    },
    handleFormatError (file) {
      this.$Message.error('文件 ' + file.name + ' 格式不正确，请选择图片文件。')
    },
    handleBeforeUpload (file) {
      if (file.size > 500 * 1024) {
        this.$Message.error("图片大小不能超过500KB");
        return;
      }
    },
    handleProgress (event, file) { },
    handleSuccess (event, file, fileList) {
      this.formValidate.cover = file.response.domain + file.response.key
    },
    handleError (event, file) { },
    handleView (img_url) {
      this.imgName = img_url
      this.visible = true
    },
    handleRemove () {
      this.formValidate.cover = '';
    },
    handleSubmit () {
      let index = 0;
      if (this.formValidate.name == '') {
        this.$Message.error("请输入商品名称"); return;
      }
      if (this.formValidate.cover == '') {
        this.$Message.error("请上传商品封面图"); return;
      }
      if (this.formValidate.cate_id == 0) {
        this.$Message.error("请选择商品分类"); return;
      }
      if (this.formValidate.content == '') {
        this.$Message.error("请输入商品内容"); return;
      }
      if (this.formValidate.unit == '') {
        this.$Message.error("请输入商品单位"); return;
      }
      // if (this.formValidate.specs_ids == '') {
      //     this.$Message.error("请选择商品规格");return;
      // }
      for (let i = 0; i < this.price_list.length; i++) {
        if (this.price_list[i].specs_price == '') {
          index = 1;
          break;
        }
      }
      if (this.formValidate.specs_ids != '' && index) {
        this.$Message.error('请完善商品价格'); return;
      }
      if (this.formValidate.specs_ids == '' && !this.formValidate.price) {
        this.$Message.error('请输入商品价格'); return;
      }
      //console.log(this.formValidate);return;
      editGood(this.formValidate).then(res => {
        if (res.code === 0) {
          this.$Message.success('操作成功')
          this.edit = false
          this.getGoodList()
        } else {
          this.$Message.error(res.text)
        }
      })
    },
    handleSubmitPrice () {
      let index = 0;
      for (let i = 0; i < this.price_list.length; i++) {
        if (this.price_list[i].specs_price == '') {
          index = 1;
          break;
        }
      }
      if (index) {
        this.$Message.error('请先完善商品价格'); return;
      }
      this.set_good_price = false
      this.formValidate.specs_price_str = JSON.stringify(this.price_list)
      //console.log(this.price_list)
    },
    async init () {
      let qiniu = await getQiniu()
      this.upload_token = qiniu.token
      this.qiniu_url = qiniu.url
    },
    getGoodList () {
      goodList(this.filter).then(res => {
        if (res.code == 0) {
          this.list = res.data
          this.loading = false
          this.pagenation.currentPage = parseInt(res.currentPage) + 1
          this.pagenation.totalPage = parseInt(res.totalPage)
          this.pagenation.perPage = parseInt(res.perPage)
        }
      })
    },
  },
  mounted () {
    this.init();
    this.getGoodList()
    let obj = {}
    obj.type = 2
    cateListForSelect(obj).then(res => {
      this.cate_list = res.data
    })
  }
}
</script>
